package com.sczmgk.hotline.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract;
import android.widget.Toast;

import com.sczmgk.hotline.constant.Constant;

import java.util.Calendar;
import java.util.TimeZone;

/**
 * Created by Administrator on 2016/6/21.
 */
public class CalenderUtils {

    private final String TAG = CalenderUtils.class.getSimpleName();
    //Android2.2版本以后的URL，之前的就不写了
    private static String calanderURL = "content://com.android.calendar/calendars";
    private static String calanderEventURL = "content://com.android.calendar/events";
    private static String calanderRemiderURL = "content://com.android.calendar/reminders";
    private static Context context;
    private static CalenderUtils instance;

    private CalenderUtils(Context context) {
        this.context = context;
    }

    public static CalenderUtils getInstance(Context context) {

        if (instance == null) {
            instance = new CalenderUtils(context);
        }
        return instance;
    }

    /**
     * 写入事件
     */
    public void writeEvent(String title, String description, String eventLocation, String date) {

        // 获取要出入的gmail账户的id

        int year = Integer.valueOf(date.substring(0, 4));
        int month = Integer.valueOf(date.substring(5, 7));
        int day = Integer.valueOf(date.substring(8, 10));
        int hourOfDay = Integer.valueOf(date.substring(11, 13));
        int minute = Integer.valueOf(date.substring(14, 16));
        String calId = "";
        Cursor userCursor = context.getContentResolver().query(Uri.parse(calanderURL), null, null, null, null);
        String name = (String) SpfUtil.getValue(context, Constant.KEY_RAEL_NAME, "");
        while (userCursor.moveToNext()) {
            //找到当前用户的Id
            String name1 = userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.NAME));
            if (name.equals(name1)) {
                calId = userCursor.getString(userCursor.getColumnIndex("_id"));
                break;
            }
        }

        //判断日程是否存在
        boolean isExist =  readEvent(description);
        if(isExist){
            MyLog.e(TAG,"日程已存在,不用再次写入");
            return;
        }

        ContentValues event = new ContentValues();
        event.put(EventsColumns.TITLE, title);
        event.put(EventsColumns.DESCRIPTION, description);
        // 插入账户
        event.put(EventsColumns.CALENDAR_ID, calId);
        event.put(EventsColumns.EVENT_LOCATION, eventLocation);
        //实例化日历
        Calendar mCalendar = Calendar.getInstance();

        //设置开始时间
        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        mCalendar.set(Calendar.MINUTE, minute);

        mCalendar.set(Calendar.YEAR,year);
        mCalendar.set(Calendar.MONTH,month-1);//月份为什么要减 1
        mCalendar.set(Calendar.DAY_OF_MONTH,day);

        long start = mCalendar.getTime().getTime();

        //设置结束时间
        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay+1);
        long end = mCalendar.getTime().getTime();


        //写入开始时间
        event.put(EventsColumns.DTSTART, start);
        //写入结束时间
        event.put(EventsColumns.DTEND, end);
        //设置有报警
        event.put(EventsColumns.HAS_ALARM, 1);
        //设置时区
        event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Shanghai");  //这个是时区，必须有，
        //添加事件
        Uri newEvent = context.getContentResolver().insert(Uri.parse(calanderEventURL), event);
        //事件提醒的设定
        long id = Long.parseLong(newEvent.getLastPathSegment());
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Instances.EVENT_ID, id);
        // 提前10分钟有提醒
        values.put(EventsColumns.MINUTES, 10);
        //插入日历
        context.getContentResolver().insert(Uri.parse(calanderRemiderURL), values);

        Toast.makeText(context, "插入事件成功!!!", Toast.LENGTH_LONG).show();
    }

    /**
     * 读取事件
     */
    public boolean readEvent(String description) {
        Cursor eventCursor = context.getContentResolver().query(Uri.parse(calanderEventURL), null, null, null, null);
        int count = eventCursor.getCount();
        while(eventCursor.moveToNext()){
            for(int i = 0; i<count;i++){
                String description1 = eventCursor.getString(eventCursor.getColumnIndex(EventsColumns.DESCRIPTION));
                if(description.equals(description1)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 删除用户
     */
    public void deleteUser() {
        int rownum = context.getContentResolver().delete(Uri.parse(calanderURL), "_id!=-1", null);  //注意：会全部删除所有账户，新添加的账户一般从id=1开始，
        //可以令_id=你添加账户的id，以此删除你添加的账户
        Toast.makeText(context, "删除了: " + rownum, Toast.LENGTH_LONG).show();
    }

    /**
     * 读取帐户
     */
    public void readUser() {
        Cursor userCursor = context.getContentResolver().query(Uri.parse(calanderURL), null, null, null, null);
        MyLog.i(TAG, "帐户数量是：" + userCursor.getCount());
        for (userCursor.moveToFirst(); !userCursor.isAfterLast(); userCursor.moveToNext()) {
            MyLog.d(TAG, "ACCOUNT_NAME：" + userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.ACCOUNT_NAME)));
            MyLog.d(TAG, "NAME：" + userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.NAME)));
            MyLog.d(TAG, "CALENDAR_DISPLAY_NAME：" + userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)));
            MyLog.d(TAG, "OWNER_ACCOUNT：" + userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.OWNER_ACCOUNT)));
        }
    }


    /**
     * 添加账户
     */

    public void initCalendars(String name, String accountName, String accountType, String calderDisplayName, String ownerAccount) {

        if (Tools.isEmpty(name)) {
            return;
        }
        Cursor userCursor = context.getContentResolver().query(Uri.parse(calanderURL), null, null, null, null);
        MyLog.i(TAG, "帐户数量是：" + userCursor.getCount());
        for (userCursor.moveToFirst(); !userCursor.isAfterLast(); userCursor.moveToNext()) {
            String name1 = userCursor.getString(userCursor.getColumnIndex(CalendarContract.Calendars.NAME));
            if (name.equals(name1)) {
                MyLog.e(TAG, name + "--> 已存在,不能重复添加");
                return;
            }
        }


        TimeZone timeZone = TimeZone.getDefault();
        ContentValues value = new ContentValues();
        value.put(CalendarContract.Calendars.NAME, name);
        value.put(CalendarContract.Calendars.ACCOUNT_NAME, accountName);
        value.put(CalendarContract.Calendars.ACCOUNT_TYPE, accountType);
        value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, calderDisplayName);
        value.put(CalendarContract.Calendars.VISIBLE, 1);
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, -9206951);
        value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
        value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, ownerAccount);
        value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

        Uri calendarUri = CalendarContract.Calendars.CONTENT_URI;
        calendarUri = calendarUri.buildUpon()
                .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType)
                .build();

        context.getContentResolver().insert(calendarUri, value);//插入用户
    }

    /**
     * Columns from the Events table that other tables join into themselves.
     */
    protected interface EventsColumns {

        public static final String CALENDAR_ID = "calendar_id";

        public static final String TITLE = "title";

        public static final String DESCRIPTION = "description";

        public static final String EVENT_LOCATION = "eventLocation";

        public static final String EVENT_COLOR = "eventColor";

        public static final String EVENT_COLOR_KEY = "eventColor_index";

        public static final String DISPLAY_COLOR = "displayColor";

        public static final String STATUS = "eventStatus";

        public static final int STATUS_TENTATIVE = 0;
        public static final int STATUS_CONFIRMED = 1;
        public static final int STATUS_CANCELED = 2;

        public static final String SELF_ATTENDEE_STATUS = "selfAttendeeStatus";

        public static final String SYNC_DATA1 = "sync_data1";

        public static final String SYNC_DATA2 = "sync_data2";

        public static final String SYNC_DATA3 = "sync_data3";

        public static final String SYNC_DATA4 = "sync_data4";

        public static final String SYNC_DATA5 = "sync_data5";

        public static final String SYNC_DATA6 = "sync_data6";

        public static final String SYNC_DATA7 = "sync_data7";

        public static final String SYNC_DATA8 = "sync_data8";

        public static final String SYNC_DATA9 = "sync_data9";

        public static final String SYNC_DATA10 = "sync_data10";

        public static final String LAST_SYNCED = "lastSynced";

        public static final String DTSTART = "dtstart";

        public static final String DTEND = "dtend";

        public static final String DURATION = "duration";

        public static final String EVENT_TIMEZONE = "eventTimezone";

        public static final String EVENT_END_TIMEZONE = "eventEndTimezone";

        public static final String ALL_DAY = "allDay";

        public static final String ACCESS_LEVEL = "accessLevel";

        public static final int ACCESS_DEFAULT = 0;

        public static final int ACCESS_CONFIDENTIAL = 1;

        public static final int ACCESS_PRIVATE = 2;

        public static final int ACCESS_PUBLIC = 3;

        public static final String AVAILABILITY = "availability";

        public static final int AVAILABILITY_BUSY = 0;

        public static final int AVAILABILITY_FREE = 1;

        public static final int AVAILABILITY_TENTATIVE = 2;

        public static final String HAS_ALARM = "hasAlarm";

        public static final String HAS_EXTENDED_PROPERTIES = "hasExtendedProperties";

        public static final String RRULE = "rrule";

        public static final String RDATE = "rdate";

        public static final String EXRULE = "exrule";

        public static final String EXDATE = "exdate";

        public static final String ORIGINAL_ID = "original_id";

        public static final String ORIGINAL_SYNC_ID = "original_sync_id";

        public static final String ORIGINAL_INSTANCE_TIME = "originalInstanceTime";

        public static final String ORIGINAL_ALL_DAY = "originalAllDay";

        public static final String LAST_DATE = "lastDate";

        public static final String HAS_ATTENDEE_DATA = "hasAttendeeData";

        public static final String GUESTS_CAN_MODIFY = "guestsCanModify";

        public static final String GUESTS_CAN_INVITE_OTHERS = "guestsCanInviteOthers";

        public static final String GUESTS_CAN_SEE_GUESTS = "guestsCanSeeGuests";

        public static final String ORGANIZER = "organizer";

        public static final String IS_ORGANIZER = "isOrganizer";

        public static final String CAN_INVITE_OTHERS = "canInviteOthers";

        public static final String CUSTOM_APP_PACKAGE = "customAppPackage";

        public static final String CUSTOM_APP_URI = "customAppUri";

        public static final String UID_2445 = "uid2445";

        public static final String MINUTES = "minutes";
    }
}
